package com.jibei.mendo.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cosofteck.gpiodemo.GpioControl;
import com.jibei.mendo.MendoApplication;
import com.jibei.mendo.R;
import com.jibei.mendo.adapter.CheckDevAdapter;
import com.jibei.mendo.adapter.CheckPortAdapter;
import com.jibei.mendo.adapter.ExigenceStopAdapter;
import com.jibei.mendo.bean.ConfigInfoBean;
import com.jibei.mendo.bean.IgnitionInfoBean;
import com.jibei.mendo.bean.MatrixInfoBean;
import com.jibei.mendo.event.Event;
import com.jibei.mendo.service.MendoService;
import com.jibei.mendo.utils.Constant;
import com.jibei.mendo.utils.EventBusUtil;
import com.jibei.mendo.utils.ProtectProcessUtil;
import com.jibei.mendo.utils.SendCommandUtil;
import com.jibei.mendo.utils.SerialPortUtil;
import com.jibei.mendo.utils.ThreadPoolUtils;
import com.jibei.mendo.utils.TimeCodeSerial;
import com.jibei.mendo.utils.TimeUtil;
import com.jibei.mendo.utils.VibratorUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * Created by Devin on 2019/8/10.
 * 主页面
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, CheckDevAdapter.CheckDevListener,
        MendoService.OnTotalTimerCountDownListener, MendoService.OnItemTimerCountDownListener,
        ExigenceStopAdapter.ExigenceStopListener, MendoService.OnProtectProcessListener {
    public boolean isMusicContinue=false;
    public static boolean isClient2ServerSuccess = false;
    public static boolean isServer2ClientSuccess = false;
    private RelativeLayout layout_main;
    private Button btn_file;
    private Button btn_setting;
    private Button btn_about;
    private RelativeLayout rl_launch_bg;
    public ImageView iv_check_on;
    public ImageView iv_check_off;
    public String id_show,role_show;
    public static boolean isClientReFire = false;
    //检测页面
    private RelativeLayout rl_jian_ce;
    private List<String> devStrings = new ArrayList<>();
    private RecyclerView rv_main_dev;
    private CheckDevAdapter mCheckDevAdapter;
    private List<String> portStrings = new ArrayList<>();
    private RecyclerView rv_main_port;
    private CheckPortAdapter mCheckPortAdapter;
    private TextView tv_check_error_list;
    private TextView tv_config_error_list;
    private RelativeLayout rl_loading_view;

    //点火页面
    private RelativeLayout rl_dian_huo;
    private ImageView iv_li_ji_stop;
    private TextView tv_total_timer;
    private TextView tv_item_next_timer;
    private LinearLayout ll_dian_wei;
    private List<Button> buttonList = new ArrayList<>();
    private RecyclerView rv_dian_wei;
    private List<String> exigenceStopLists = new ArrayList<>();
    private ExigenceStopAdapter exigenceStopAdapter;
    private TextView tv_ready_error_list;
    private TextView tv_release_error_list;

    //设置和显示状态相关
    private Button btn_auto_manu;
    private TextView tv_master_slaver;
    private TextView tv_device_id;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        layout_main = findViewById(R.id.layout_main);
        rl_launch_bg = findViewById(R.id.rl_launch_bg);
        btn_file = findViewById(R.id.btn_file);
        btn_setting = findViewById(R.id.btn_setting);
        btn_about = findViewById(R.id.btn_about);
        iv_check_on = findViewById(R.id.iv_check_on);
        iv_check_off = findViewById(R.id.iv_check_off);
        tv_master_slaver = findViewById(R.id.tv_master_slaver);
        tv_device_id = findViewById(R.id.tv_device_id);
        btn_about.setOnClickListener(this);
        btn_file.setOnClickListener(this);
        btn_setting.setOnClickListener(this);
        iv_check_on.setOnClickListener(this);
        iv_check_off.setOnClickListener(this);

        MendoService.setOnTimerCountDownListener(this, this);
        MendoService.setOnProtectProcessListener(this);
        //默认PG9，低电平
        offPower();

        //检测相关
        rl_jian_ce = findViewById(R.id.rl_jian_ce);

        rv_main_dev = findViewById(R.id.rv_main_dev);
        rv_main_dev.setLayoutManager(new LinearLayoutManager(this));
        mCheckDevAdapter = new CheckDevAdapter(this, devStrings, this);
        rv_main_dev.setAdapter(mCheckDevAdapter);

        rv_main_port = findViewById(R.id.rv_main_port);
        rv_main_port.setLayoutManager(new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false));
        rv_main_port.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mCheckPortAdapter = new CheckPortAdapter(this, portStrings);
        rv_main_port.setAdapter(mCheckPortAdapter);
        tv_check_error_list = findViewById(R.id.tv_check_error_list);
        tv_config_error_list = findViewById(R.id.tv_config_error_list);
        rl_loading_view = findViewById(R.id.rl_loading_view);

        //点火相关
        rl_dian_huo = findViewById(R.id.rl_dian_huo);
        iv_li_ji_stop = findViewById(R.id.iv_li_ji_stop);
        iv_li_ji_stop.setOnClickListener(this);
//        iv_li_ji_stop.setVisibility(View.INVISIBLE);
        tv_total_timer = findViewById(R.id.tv_total_timer);
        tv_item_next_timer = findViewById(R.id.tv_item_next_timer);
        ll_dian_wei = findViewById(R.id.ll_dian_wei);
        rv_dian_wei = findViewById(R.id.rv_dian_wei);
        rv_dian_wei.setLayoutManager(new GridLayoutManager(this, 2, GridLayoutManager.HORIZONTAL, false));
        exigenceStopAdapter = new ExigenceStopAdapter(this, exigenceStopLists, this);
        rv_dian_wei.setAdapter(exigenceStopAdapter);
        tv_ready_error_list = findViewById(R.id.tv_ready_error_list);
        tv_release_error_list = findViewById(R.id.tv_release_error_list);

        //设置和状态显示相关
        btn_auto_manu = findViewById(R.id.btn_auto_manu);
        tv_master_slaver = findViewById(R.id.tv_master_slaver);
        btn_auto_manu.setOnClickListener(this);

    }

    boolean isActive_auto_manu = false;

    @Override
    public void onClick(View v) {
        VibratorUtil.getInstance().executeVibrator(this, 100);
        switch (v.getId()) {
            case R.id.btn_file:
                startActivity(new Intent(this, FileActivity.class));
                break;
            case R.id.btn_setting:
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.btn_about:
                startActivity(new Intent(this, AboutDevActivity.class));
                break;
            case R.id.iv_check_on:
                offPower();
                break;
            case R.id.iv_check_off:
                onPower();
                break;
            case R.id.iv_li_ji_stop:
                //急停按钮
                exigenceStop();
                break;
            case R.id.btn_auto_manu:
                //自动点火手动点火切换功能
                if (isActive_auto_manu == false) {
                    Log.d("lhl", "自动切换");
                    btn_auto_manu.setText(getResources().getString(R.string.fire_switch_manual));
                    EventBusUtil.getInstance().postEvent(new Event(Constant.Events.AUTO_MANU_FIRE_M));
                    isActive_auto_manu = true;
                } else {
                    btn_auto_manu.setText(getResources().getString(R.string.fire_switch_auto));
                    EventBusUtil.getInstance().postEvent(new Event(Constant.Events.AUTO_MANU_FIRE_A));
                    isActive_auto_manu = false;
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("lhl", "MainActivity   onResume()");
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rl_loading_view.setVisibility(View.GONE);
    }


    @Override
    public boolean onActivityReceiveEvents(Event event) {
        boolean isCaptured = false;//子Activity是否捕获事件
        if (super.onActivityReceiveEvents(event)) {
            return isCaptured;
        }
        isCaptured = true;
        switch (event.getTag()) {
            case Constant.Events.DIAN_HUO:
                //                rl_launch_bg.setBackgroundColor(getResources().getColor(R.color.bg_color));
                AtomicInteger temp_e = (AtomicInteger) event.data;
                Log.d("lhl", " dianhuo Event found event data :" + temp_e);
                showDianHuoView(temp_e);
                //填充ID 和 角色
                tv_master_slaver.setText(SPUtils.getInstance().getInt(Constant.MASTERSLAVER)==1?"Master":"Slaver");
                tv_device_id.setText(SPUtils.getInstance().getString(Constant.LOCALID));
                break;
            case Constant.Events.JIAN_CE:
                //                rl_launch_bg.setBackgroundColor(getResources().getColor(R.color.bg_color));

                showJianCeView();
                break;
            case Constant.Events.KONG_DANG:
                //                rl_launch_bg.setBackgroundColor(getResources().getColor(R.color.bg_color));
                showMainView();
                break;
            case Constant.Events.READY_PRESS:
                Log.d("lhl", "EventBus   MainActivity   Receive>>>ready");//预备
                //                startActivity(new Intent(this, ReadyActivity.class));
                break;
            case Constant.Events.DIAN_HUO_PRESS:
                Log.d("lhl", "EventBus   MainActivity   Receive>>>dian huo");//点火
                break;
            case Constant.Events.EXCEL_TOTAL_TIMER:
                String totalStr = (String) event.data;
                tv_total_timer.setText(totalStr);
                break;
            case Constant.Events.EXCEL_ITEM_NEXT_TIMER:
                String itemStr = (String) event.data;
                tv_item_next_timer.setText(itemStr);
                break;
            case Constant.Events.COMMAND_READY_ERROR_LIST:
                String readyErrorList = (String) event.data;
                if (readyErrorList.length() <= 2) {
                    readyErrorList = "OK";
                    //GpioControl.writeGpioValue(Constant.PG.PG4, 1);//预备LED灯亮
                }
                tv_ready_error_list.setText(getResources().getString(R.string.charge_fial) + readyErrorList);
                break;
            case Constant.Events.COMMAND_RELEASE_ERROR_LIST:
                String releaseErrorList = (String) event.data;
                if (releaseErrorList.length() <= 2) {
                    releaseErrorList = "OK";
                }
                tv_release_error_list.setText(getResources().getString(R.string.discharge_fial)+ releaseErrorList);
                break;
            case Constant.Events.COMMAND_CHECK_ERROR_LIST:
                String checkErrorList = (String) event.data;
                tv_check_error_list.setText(getResources().getString(R.string.device_detect) + checkErrorList);
                break;
            case Constant.Events.COMMAND_CONFIG_ERROR_LIST:
                String configErrorList = (String) event.data;
                tv_config_error_list.setText(getResources().getString(R.string.download_detect)+ configErrorList);
                rl_loading_view.setVisibility(View.GONE);
                break;
            case Constant.Events.UPDATEUI:
                iv_check_on.setVisibility(View.GONE);
                iv_check_off.setVisibility(View.VISIBLE);

                break;
            case Constant.Events.UPDATE_DIANHUO_INIT_VIEW:
//                int temp = (int) event.data;
//                List<IgnitionInfoBean> ignitionInfoList = MendoApplication.getApplication().getDaoSession().getIgnitionInfoBeanDao().queryBuilder().list();
//                String finalTime = ignitionInfoList.get(ignitionInfoList.size() - 1 - temp).getTime();
//                long deltaTime = TimeUtil.getInstance().timeToMillisecond(ignitionInfoList.get(temp).getTime()) - TimeUtil.getInstance().timeToMillisecond(ignitionInfoList.get(temp - 1).getTime());
//                tv_total_timer.setText(finalTime);
//                tv_item_next_timer.setText(TimeUtil.getInstance().millisecondToTime(deltaTime));
                break;
            case Constant.Events.GLOBLE_ID:
                 id_show = (String)event.data;//vent.data

//                tv_device_id.setText(id_show);
                break;
            case Constant.Events.GLOBLE_ROLE:
//                role_show = (String)event.data;
//                tv_master_slaver.setText(role_show);
                break;
            case Constant.Events.POSTFIRECMD:
                String re = (String)event.data;
                if (re.equals("Fire"))
                {
                    isClientReFire = true;
                    Log.d(Constant.TAG,"接收到了接收线程的点火命令");
                }
                if(re.equals("FireRED"))
                {
                    isClientReFire = false;
                    Log.d(Constant.TAG,"已经在点火了");
                }
                break;
            case Constant.Events.TIME_CODE_BYTE_ARRAY:
                byte tc[] = new byte[20];
                tc[10] = (byte)event.data;
                isMusicContinue = true;
//                Disposable disposable = Observable.timer(100, TimeUnit.MILLISECONDS)
//                        .subscribe(aLong -> { isMusicContinue = false;});
//                while (isMusicContinue) {
//                    if (last_raw_rec!=tc[10]) {
//                        disposable.dispose();
//                        isMusicContinue= true;
//                    }
//                }
                Log.d("ly","isMusicContinue:"+isMusicContinue);
                //last_raw_rec = tc[10];
                break;
            case Constant.Events.ID_FROM_EXCEL:
                id_show = (String)event.data;
                tv_device_id.setText(id_show);
                break;
            case Constant.Events.ROLE_FROM_EXCEL:
                role_show = (String)event.data;
                if(role_show.equals("1"))
                {
                    role_show = "Master";
                    SPUtils.getInstance().put(Constant.MASTERSLAVER, 1);//存储角色
                }
                if(role_show.equals("2"))
                {
                    role_show = "Slaver";
                    SPUtils.getInstance().put(Constant.MASTERSLAVER, 2);//存储角色
                }
                tv_master_slaver.setText(role_show);
                break;
            case Constant.Events.CLIENT2SERVERSUCCESS:
                isClient2ServerSuccess = true;
                break;
            case Constant.Events.SERVER2CLIENTSUCCESS:
                isServer2ClientSuccess = true;
                break;
            default:
                isCaptured = false;
                break;
        }
        return isCaptured;
    }

    /**
     * 展示点火界面
     */
    private void showDianHuoView(AtomicInteger time) {

        ToastUtils.showLong(getResources().getString(R.string.power_ok_fire_after_4s));
        iv_check_on.setVisibility(View.VISIBLE);
        iv_check_off.setVisibility(View.GONE);
        iv_check_on.setPressed(true);
        iv_check_on.setPressed(true);
        GpioControl.writeGpioValue(Constant.PG.PG4, 0);//预备LED灯灭
        GpioControl.writeGpioDirection(Constant.PG.PG9, 1);//设置PG9为输出状态
        GpioControl.writeGpioValue(Constant.PG.PG9, 1);//拉高PG9
        layout_main.setVisibility(View.GONE);
        rl_dian_huo.setVisibility(View.VISIBLE);
        rl_jian_ce.setVisibility(View.GONE);

        rl_launch_bg.setBackgroundColor(getResources().getColor(R.color.bg_color));

        //清空
        tv_ready_error_list.setText(getResources().getString(R.string.charge_fial));
        tv_release_error_list.setText(getResources().getString(R.string.discharge_fial));
        List<IgnitionInfoBean> ignitionInfoList = MendoApplication.getApplication().getDaoSession().getIgnitionInfoBeanDao().queryBuilder().list();
        Log.d("lhl", "time:" + time);
        if (time.get() != 0) {
            String finalTime = TimeUtil.getInstance().millisecondToTime(TimeUtil.getInstance().timeToMillisecond(ignitionInfoList.get(ignitionInfoList.size() - 1 - time.get()).getTime()) - TimeUtil.getInstance().timeToMillisecond(ignitionInfoList.get(0).getTime()));
            long deltaTime = TimeUtil.getInstance().timeToMillisecond(ignitionInfoList.get(time.get()).getTime()) - TimeUtil.getInstance().timeToMillisecond(ignitionInfoList.get(time.get() - 1).getTime());
            tv_total_timer.setText(finalTime);
            tv_item_next_timer.setText(TimeUtil.getInstance().millisecondToTime(deltaTime));
        } else {
            try {
                String finalTime = ignitionInfoList.get(ignitionInfoList.size() - 1).getTime();
                //long deltaTime = TimeUtil.getInstance().timeToMillisecond(ignitionInfoList.get(time).getTime()) - TimeUtil.getInstance().timeToMillisecond(ignitionInfoList.get(time - 1).getTime());
                tv_total_timer.setText(finalTime);
                tv_item_next_timer.setText(ignitionInfoList.get(0).getTime());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //急停相关
        List<MatrixInfoBean> matrixInfoBeanList = MendoApplication.getApplication().getDaoSession().getMatrixInfoBeanDao().queryBuilder().list();
        if (matrixInfoBeanList != null && matrixInfoBeanList.size() > 0) {
            Log.d("lhl", "found a matrix list here");
            createExigenceStopTabLayout(matrixInfoBeanList);
            //第一个急停矩阵中的从机
            exigenceStopLists.clear();
            exigenceStopLists.addAll(matrixInfoBeanList.get(0).getVidLists());
            exigenceStopAdapter.notifyDataSetChanged();
        }


    }

    /**
     * 展示检测界面
     */
    @SuppressLint("CheckResult")
    private void showJianCeView() {
        iv_check_on.setVisibility(View.VISIBLE);
        iv_check_off.setVisibility(View.GONE);
        iv_check_on.setPressed(true);
        GpioControl.writeGpioValue(Constant.PG.PG4, 0);//预备LED灯灭
        //拉高PG9
        GpioControl.writeGpioDirection(Constant.PG.PG9, 1);//设置PG9为输出状态
        GpioControl.writeGpioValue(Constant.PG.PG9, 1);//拉高PG9
        layout_main.setVisibility(View.GONE);
        rl_dian_huo.setVisibility(View.GONE);
        rl_jian_ce.setVisibility(View.VISIBLE);

        //清空
        tv_check_error_list.setText(getResources().getString(R.string.processing));
        tv_config_error_list.setText("");
        portStrings.clear();
        mCheckPortAdapter.notifyDataSetChanged();


        rl_loading_view.setVisibility(View.VISIBLE);
        rl_launch_bg.setBackgroundColor(getResources().getColor(R.color.bg_color));

        //发送自检命令成功后再发配置命令
        List<ConfigInfoBean> configInfoBeanList = MendoApplication.getApplication().getDaoSession().getConfigInfoBeanDao().queryBuilder().list();


        if (configInfoBeanList != null && configInfoBeanList.size() > 0) {
            ToastUtils.showLong(getResources().getString(R.string.read_ok_detecting));
            devStrings.clear();

            for (int i = 0; i < configInfoBeanList.size(); i++) {
                ConfigInfoBean configInfoBean = configInfoBeanList.get(i);
                devStrings.add(configInfoBean.getVid());
            }
            mCheckDevAdapter.notifyDataSetChanged();

            Observable.timer(3500, TimeUnit.MILLISECONDS)//3500ms
                    .subscribe(aLong -> {
                        sendCheckCommand(configInfoBeanList);
                    });
        } else
            ToastUtils.showLong(getResources().getString(R.string.read_file_fail));


    }

    /**
     * 展示主界面
     */
    private void showMainView() {
        layout_main.setVisibility(View.VISIBLE);
        rl_jian_ce.setVisibility(View.GONE);
        rl_dian_huo.setVisibility(View.GONE);
        rl_launch_bg.setBackgroundColor(getResources().getColor(R.color.bg_color));
        GpioControl.writeGpioValue(Constant.PG.PG4, 0);//预备LED灯灭
        GpioControl.writeGpioValue(Constant.PG.PG5, 0);//点火LED灯灭
    }

    @Override
    public void onCheckDevListener(View mView, int position) {
        VibratorUtil.getInstance().executeVibrator(this, 100);
        List<ConfigInfoBean> configInfoBeanList = MendoApplication.getApplication().getDaoSession().getConfigInfoBeanDao().queryBuilder().list();
        List<ConfigInfoBean> configInfoBeans = new ArrayList<>();
        configInfoBeans.add(configInfoBeanList.get(position));
        sendCheckCommand(configInfoBeans);
    }

    /**
     * 发送自检命令
     */
    private void sendCheckCommand(List<ConfigInfoBean> configInfoBeanList) {
        ThreadPoolUtils.execute(() -> {
            if (configInfoBeanList != null && configInfoBeanList.size() > 0) {
                Map<String, List<String>> stringListMap = SendCommandUtil.getInstance().sendCheckCommand(configInfoBeanList);
                try {
                    portStrings.clear();
                    portStrings.addAll(stringListMap.get(configInfoBeanList.get(0).getVid()));
                    runOnUiThread(() -> {
                        mCheckPortAdapter.notifyDataSetChanged();
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 急停按钮：停止当前页面的某个从机或者某几个从机
     */
    //SerialPortUtil.getInstance().sendCommandWithBackDelay("F0FF02E7FF", 100);
    private void exigenceStop() {
        List<ConfigInfoBean> configInfoBeanList = MendoApplication.getApplication().getDaoSession().getConfigInfoBeanDao().queryBuilder().list();
        if (configInfoBeanList != null && configInfoBeanList.size() > 0) {
//            for (int i = 0; i < configInfoBeanList.size(); i++) {
                try {
                    SerialPortUtil.getInstance().sendCommandWithBackDelay("F0FF02E7FF", 100);
//                    boolean isSendSuccess = SerialPortUtil.getInstance().sendCommand(
//                            "F0" + configInfoBeanList.get(i).getVid() + "02E701",
//                            "F0" + configInfoBeanList.get(i).getVid() + "03E7C0F7", 100);
//                    int errorCount = 1;
//                    if (!isSendSuccess) {
//                        while (!isSendSuccess && errorCount < 3) {
//                            isSendSuccess = SerialPortUtil.getInstance().sendCommand(
//                                    "F0" + configInfoBeanList.get(i).getVid() + "02E701",
//                                    "F0" + configInfoBeanList.get(i).getVid() + "03E7C0F7", 100);
//                            errorCount++;
//                            Log.d("lhl", "释放指令   发送失败次数>>>" + errorCount);
//                            Thread.sleep(200);
//                        }
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//            }
        }
    }

    //关于倒计时的回调方法
    @Override
    public void onTotalTick(long l) {
        tv_total_timer.setText(TimeUtil.getInstance().millisecondToTime(l));
    }

    @Override
    public void onTotalFinish() {
        tv_total_timer.setText("00:00:00.000");
    }

    @Override
    public void onItemTick(long l) {
        tv_item_next_timer.setText(TimeUtil.getInstance().millisecondToTime(l));
    }

    @Override
    public void onItemFinish() {
        tv_item_next_timer.setText("00:00:00.000");
        VibratorUtil.getInstance().executeVibrator(this, 20);
    }

    /**
     * 送电
     */
    private void onPower() {
        iv_check_on.setVisibility(View.VISIBLE);
        iv_check_off.setVisibility(View.GONE);
        GpioControl.writeGpioDirection(Constant.PG.PG9, 1);//设置PG9为输出状态
        GpioControl.writeGpioValue(Constant.PG.PG9, 1);//拉高PG9
    }

    /**
     * 断电
     */
    private void offPower() {
        //无返回值情况下释放电能:
        try {
            SendCommandUtil.getInstance().sendAllReleaseCommandWithNoRe();
            Thread.sleep(100);
            SendCommandUtil.getInstance().sendAllReleaseCommandWithNoRe();
            Thread.sleep(500);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.d("lhl", "发送无返回值释放命令成功");
        iv_check_on.setVisibility(View.GONE);
        iv_check_off.setVisibility(View.VISIBLE);
        GpioControl.writeGpioDirection(Constant.PG.PG9, 1);//设置PG9为输出状态
        GpioControl.writeGpioValue(Constant.PG.PG9, 0);//拉低PG9
    }

    /**
     * 创建急停的TabLayout
     *
     * @param matrixInfoBeanList list
     */
    private void createExigenceStopTabLayout(List<MatrixInfoBean> matrixInfoBeanList) {
        //Log.d("ly","加载了急停layout，尺寸为："+matrixInfoBeanList.size()+"个！");
        if (matrixInfoBeanList != null && matrixInfoBeanList.size() > 0) {
            ll_dian_wei.removeAllViews();
            buttonList.clear();
            Log.d("ly","加载了急停layout，尺寸为："+matrixInfoBeanList.size()+"个！");
            for (int i = 0; i < matrixInfoBeanList.size(); i++) {
                int finalI = i;
                Button button = new Button(this);
                button.setWidth(dip2px(this, 50));//0
                button.setHeight(dip2px(this, 50));
                button.setBackgroundColor(getResources().getColor(R.color.blue));
                button.setText(matrixInfoBeanList.get(i).getMatrixId() + getResources().getString(R.string.matrix));
                button.setTextSize(16f);
                button.setGravity(Gravity.CENTER);
                button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
                buttonList.add(button);
                int finalI1 = i;
                Log.d("lhl", "touch matrix:" + finalI1);
                button.setOnClickListener(view -> {

                    for (int j = 0; j < buttonList.size(); j++) {
                        buttonList.get(j).setBackgroundColor(getResources().getColor(R.color.blue));
                        if (j == finalI) {
                            VibratorUtil.getInstance().executeVibrator(this, 100);
                            Log.d("lhl", "touch matrix:" + finalI1 + "device:" + j);
                            buttonList.get(j).setBackgroundColor(getResources().getColor(R.color.yellow));
                            exigenceStopLists.clear();
                            exigenceStopLists.addAll(matrixInfoBeanList.get(j).getVidLists());
                            exigenceStopAdapter.notifyDataSetChanged();
                        }
                    }
                });
                ll_dian_wei.addView(button);
            }
            buttonList.get(0).setBackgroundColor(getResources().getColor(R.color.yellow));
        }
    }

    //dp转为px
    private int dip2px(Context context, float dipValue) {
        Resources r = context.getResources();
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dipValue, r.getDisplayMetrics());
    }

    //急停的item点击回调
    @Override
    public void onExigenceStopListener(View mView, int position) {
        VibratorUtil.getInstance().executeVibrator(this, 100);

        mView.setBackgroundColor(getResources().getColor(R.color.yellow));
        Log.d("lhl", "此处捕捉按键——" + position);
    }

    @Override
    public void onProtectProcessListener() {
        ProtectProcessUtil.getInstance().protectProcess(this);
    }
}
